package cn.zt.middleware.dynamic.thread.pool.sdk.trigger.listener;

import cn.zt.middleware.dynamic.thread.pool.sdk.domain.IDynamicThreadPoolService;
import cn.zt.middleware.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import cn.zt.middleware.dynamic.thread.pool.sdk.registry.IRegistry;
import com.alibaba.fastjson.JSON;
import org.redisson.api.listener.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author: zhangtao
 * @description: 监听动态线程池配置变更
 * @date: 2024-08-09 15:47
 */

public class ThreadPoolConfigAdjustListener implements MessageListener<ThreadPoolConfigEntity> {


    private Logger logger = LoggerFactory.getLogger(ThreadPoolConfigAdjustListener.class);


    private final IDynamicThreadPoolService dynamicThreadPoolService;

    private final IRegistry registry;

    public ThreadPoolConfigAdjustListener(IDynamicThreadPoolService dynamicThreadPoolService, IRegistry dynamicThreadPoolRedisRegistry) {
        this.dynamicThreadPoolService = dynamicThreadPoolService;
        this.registry = dynamicThreadPoolRedisRegistry;
    }

    @Override
    public void onMessage(CharSequence charSequence, ThreadPoolConfigEntity threadPoolConfigEntity) {
        // 1. 更新线程池配置信息
        logger.info("动态线程池，调整线程池配置。线程池名称:{} 核心线程数:{} 最大线程数:{}",
                threadPoolConfigEntity.getThreadPoolName(), threadPoolConfigEntity.getPoolSize(), threadPoolConfigEntity.getMaximumPoolSize());
        dynamicThreadPoolService.updateThreadPoolConfig(threadPoolConfigEntity);
        // 2. 上报到注册中心
        // 2.1 配置列表更新
        List<ThreadPoolConfigEntity> threadPoolConfigs = dynamicThreadPoolService.queryThreadPoolConfigs();
        registry.reportThreadPoolConfigList(threadPoolConfigs);
        // 2.2 指定配置信息更新
        ThreadPoolConfigEntity threadPoolConfig = dynamicThreadPoolService.queryThreadPoolConfigByName(threadPoolConfigEntity.getThreadPoolName());
        registry.reportThreadPoolConfig(threadPoolConfig);

        logger.info("动态线程池，上报线程池配置：{}", JSON.toJSONString(threadPoolConfigEntity));

    }
}
